package xin.nick.persistence.core.manager;

import xin.nick.persistence.core.entity.Configuration;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Nick
 * @date 2021/5/25
 * @description
 */
public class TransactionalManager {

    /**
     * 当前线程的链接
     */
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    private DataSource dataSource = null;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public TransactionalManager(){

    }

    public TransactionalManager(DataSource dataSource){
        this.dataSource = dataSource;
    }
    /**
     * 获取当前线程的链接
     * @return
     */
    public Connection getCurrentThreadConn() {

        Connection conn = null;
        if(threadLocal.get() == null) {
            try {
                conn = dataSource.getConnection();
            } catch (SQLException E) {
                E.printStackTrace();
            }
        }
        return conn;
    }

    public void startTransactional() {
        try {
            getCurrentThreadConn().setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void commit() {
        try {
            getCurrentThreadConn().commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void rollback() {
        try {
            getCurrentThreadConn().rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
